#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

# used to create submit cmd of matrix.yaml
# Usage:
#   create-test-matrix matrix.yaml -c ~/repro/category.json --category_level 1,2,3 -b master
#   create-test-matrix matrix.yaml -j/--job lkp-tests/jobs/rpmbuild.yaml --srv_git /srv/git/openeuler/ -b openEuler-20.03-LTS-SP1 --commit_num 1
# eg: matrix.yaml:
# default_param:
#   runtime: 30
# common_param:
#   memory: 16G
#   os:
#     - centos
#     - openeuler

require 'optparse'
require 'open3'
require 'set'
require 'yaml'
require 'json'

LKP_SRC ||= ENV['LKP_SRC'] || '/c/lkp-tests'
SUBMIT = "#{LKP_SRC}/sbin/submit"

job_path = "#{LKP_SRC}/jobs/rpmbuild.yaml"
srv_git_path = '/srv/git/openeuler/'
upstream_branch = 'openEuler-20.03-LTS-SP1'
commit_num = 1
category_level = Set.new(['1'])
category_path = nil


def rpm_name(rpm)
  return unless rpm
  m = rpm.match(/^(.+)-.+-.+/)
  if m
    m = m.captures[0]
  else
    m =rpm
  end

  m 
end

opt_parser = OptionParser.new do |opts|
  opts.banner = 'Usage:  create-test-matrix matrix.yaml -j/--job lkp-tests/jobs/rpmbuild.yaml --srv-git /srv/git/openeuler/ -b openEuler-20.03-LTS-SP1 --commit_num 1'
  opts.separator ''

  opts.on('-j job.yaml', '--job job.yaml', 'submit with job yaml like: lkp-tests/jobs/rpmbuild.yaml') do |job|
    job_path = job
  end

  opts.on('--srv_git srv_git_path', 'srv-git path like: /srv/git/openeuler/') do |git_path|
    srv_git_path = git_path
  end

  opts.on('-b branch', '--branch', 'branch of each repo in srv-git like: openEuler-20.03-LTS-SP1') do |b|
    upstream_branch = b
  end

  opts.on('--commit_num commit_num', 'commit number of git log') do |num|
    commit_num = num
  end

  opts.on('--category_level category_level', 'submit wich repos with level like: 1 | 1,2') do |level|
    category_level = Set.new(level.split(','))
  end

  opts.on('-c category.json', 'catetory.json file path') do |file|
    category_path = file
  end


  opts.on_tail('-h', '--help', 'show this message') do
    puts opts
    exit
  end
end

argv = if ARGV == []
         ['-h']
       else
         ARGV
       end

opt_parser.parse!(argv)
unless argv[0].end_with?('yaml')
  warn 'please give a matrix.yaml'
  exit
end

unless category_path && File.exists?(category_path)
  warn 'no category file or the file does not exists'
  exit
end

category = {}
category_info = JSON.parse(File.read(category_path))
category_info.each do |rpm_info|
  pkg = rpm_info['oecp']
  
  rpm = rpm_name(pkg)
  next unless rpm
  category[rpm] = rpm_info['level'].split('level')[-1]
end



matrix = YAML.load_file(argv[0])
matrix['submit'] = []
submit_lines = []

repos = []
repros_str = Open3.capture3("ls #{srv_git_path}*/*/* |grep \.git")[0]
repros_str.split(':').each do |line|
  repos << line.lstrip
end

repos.each do |repo|
  next unless repo.end_with?('.git')

  pkg_name = repo.split('/')[5]
  level = category[pkg_name] || 'other'
  next unless category_level.include?(level)

  commit_id = %x(commit_id=$(git -C #{repo} log #{upstream_branch} -n#{commit_num} --pretty=format:%H -q); echo $i $commit_id;)
  commit_id.chomp!
  next if commit_id.empty?

  upstream_repo = (repo.gsub('.git', '')).split(srv_git_path)[-1]

  upstream_url = %x(git -C #{repo} remote -v)
  upstream_url = (upstream_url.split('(fetch)')[0].gsub('origin', '')).strip

  cmd = "#{job_path} upstream_repo=#{upstream_repo} upstream_branch=#{upstream_branch} upstream_commit=#{commit_id} upstream_url=#{upstream_url} category_level=#{level}"

  matrix['submit'] << cmd
end

File.open(argv[0], 'w') do |f|
  f.write(YAML.dump(matrix))
end
